package top.yxqz.listener.web;

import javax.servlet.ServletContext;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

/**
 * @author Mr.余
 * @date 2022/12/8
 * @package top.yxqz.listener.web
 * 监听会话
 */
@WebListener
public class SayHelloHttpSessionListener implements HttpSessionListener {
    @Override
    public void sessionCreated(HttpSessionEvent httpSessionEvent) {
        HttpSession session = httpSessionEvent.getSession(); //得到当前会话
        ServletContext servletContext = session.getServletContext(); //得到application域对象
        int people_number = (int) servletContext.getAttribute("People_number");
        servletContext.setAttribute("People_number",people_number+1);//初始化人数，清空人数，默认是0个人在线

    }

    @Override
    public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
        HttpSession session = httpSessionEvent.getSession(); //得到当前会话
        ServletContext servletContext = session.getServletContext(); //得到application域对象
        int people_number = (int) servletContext.getAttribute("People_number");
        servletContext.setAttribute("People_number",people_number-1);//初始化人数，清空人数，默认是0个人在线

    }
}
